use chrono::{DateTime, Utc};
use sqlx::SqlitePool;
use crate::db::{self, PlanWithUser};
use crate::error::AppResult;
use crate::models::{Plan, CreatePlan};
use crate::utils::time;

pub struct PlanService;

impl PlanService {
    /// 创建新计划
    pub async fn create_plan(pool: &SqlitePool, create_plan: CreatePlan) -> AppResult<Plan> {
        db::plan::create(pool, &create_plan).await
    }
    
    /// 查找待提醒的计划（包含用户信息）
    pub async fn find_pending_reminders_with_user(pool: &SqlitePool) -> AppResult<Vec<PlanWithUser>> {
        db::plan::find_pending_reminders_with_user(pool).await
    }
    
    /// 查找待提醒的计划
    pub async fn find_pending_reminders(pool: &SqlitePool) -> AppResult<Vec<Plan>> {
        db::plan::find_pending_reminders(pool).await
    }
    
    /// 处理计划提醒后的更新
    pub async fn process_reminder(pool: &SqlitePool, plan_id: i64, frequency: &str, next_reminder: DateTime<Utc>) -> AppResult<()> {
        // 首先更新 last_sent_at，防止重复发送
        db::plan::update_last_sent(pool, plan_id).await?;
        
        if frequency == "once" {
            // 单次提醒，标记为已完成
            db::plan::update_status(pool, plan_id, "completed").await?;
        } else {
            // 重复提醒，计算下次提醒时间
            if let Some(next_time) = time::calculate_next_reminder(next_reminder, frequency) {
                db::plan::update_next_reminder(pool, plan_id, next_time).await?;
            }
        }
        Ok(())
    }
    
    /// 查找用户的所有计划
    pub async fn find_user_plans(pool: &SqlitePool, user_id: i64) -> AppResult<Vec<Plan>> {
        db::plan::find_by_user_id(pool, user_id).await
    }
}
